import BaseService from './base';
import Sequelize from 'sequelize';
const Op = Sequelize.Op;

export default class IpsService extends BaseService {
  constructor({ ipsDao }) {
    super();
    this.ipsDao = ipsDao
  }

  async getIpsAll (ips) {
    const [err, list] = await this.ipsDao.getIpsAll({
      where: {
        mark: {[Op.ne]: ips.mark}
      }
    });
    if (err) {
      return this.fail('获取列表失败', null, err);
    }
    return this.success('查询成功', list);
  }

  async getIpslist(ips) {
    const [err, count, rows] = await this.ipsDao.getIpslist({
      where: {
        ips_name: ips.ips_name === '' ? {
          [Op.ne]: null
        } : ips.ips_name,
        mark: {[Op.ne]: ips.mark}
      },
      limit: ips.limit,
      offset: ips.limit * (ips.offset - 1),
      distinct: true
    });
    if (err) {
      return this.fail('获取列表失败', null, err);
    }
    return this.success('查询成功', count, rows);
  }

  async addIps(ips) {
    const [exsitErr, itemExsit] = await this.ipsDao.findOne({
      where: {
        SERVER_URL: ips.SERVER_URL
      }
    });
    if (exsitErr) {
      return this.fail('添加失败', null, exsitErr);
    }
    if (itemExsit) {
      return this.fail('已存在');
    }
    const [addErr] = await this.ipsDao.addIps(ips);
    if (addErr) {
      return this.fail('添加失败', null, addErr);
    }
    return this.success('添加成功')
  }

  async delIps(ips) {
    const [err, updateIps] = await this.ipsDao.update(ips, {
      where: {
        id: ips.id
      }
    });
    if (err) {
      return this.fail('删除失败');
    }
    return this.success('删除成功');
  }

  async updateIps(ips) {
    const [err, updateIps] = await this.ipsDao.update(ips, {
      where: {
        id: ips.id
      }
    });
    if (err) {
      return this.fail('更新失败');
    }
    return this.success('更新成功');
  }
}